package com.digiwin.demo.influx;//package com.digiwin.demo.influx;


import lombok.SneakyThrows;
import org.influxdb.BatchOptions;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @Author yanggld
 * @Date 2020/1/3-9:31
 * @Description
 */
public class InfluxDBManagementExample {


	public static void main(final String[] args) throws InterruptedException {
		InfluxDB influxDB = InfluxDBFactory.connect("https://ts-bp19iv1y835254758.influxdata.rds.aliyuncs.com:3242", "digiwin", "digiwin&1982");
		String dbName = "aTimeSeries";
		influxDB.setDatabase(dbName);
//		influxDB.query(new Query("CREATE DATABASE " + dbName));
		String rpName = "aRetentionPolicy";
//		influxDB.query(new Query("CREATE RETENTION POLICY " + rpName + " ON " + dbName + " DURATION 30h REPLICATION 2 SHARD DURATION 30m DEFAULT"));
		influxDB.setRetentionPolicy(rpName);

//		influxDB.enableBatch(BatchOptions.DEFAULTS);
		influxDB.enableBatch(20,20, TimeUnit.MILLISECONDS);

		int i = 100;
		for (int i1 = 0; i1 < i; i1++) {
			new Thread(new TaskThread(influxDB)).start();
		}
//
//		influxDB.write(Point.measurement("disk")
//				.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
//				.addField("used", 80L)
//				.addField("free", 1L)
//				.build());
//
//		Query query = new Query("SELECT idle FROM cpu", dbName);
//		QueryResult query1 = influxDB.query(query);
//		System.out.println(query1.toString());
//		Query query2 = new Query("SELECT COUNT(idle) FROM cpu", dbName);
//		QueryResult result2 = influxDB.query(query2);
//		System.out.println(result2.toString());
//		influxDB.query(new Query("DROP RETENTION POLICY " + rpName + " ON " + dbName));
//		influxDB.query(new Query("DROP DATABASE " + dbName));
		influxDB.close();
	}
}

class TaskThread implements Runnable{
	private InfluxDB influxDB;
	public TaskThread(InfluxDB influxDB) {
		this.influxDB = influxDB;
	}

	@SneakyThrows
	@Override
	public void run() {
		int i = 0;
		while (i<10000) {
			long random = ThreadLocalRandom.current().nextLong(5);
			Point point = Point.measurement("cpu")
					.time(Instant.now().getEpochSecond(), TimeUnit.SECONDS)
					.addField("idle", 90L - random)
					.addField("user", 9L + random)
					.addField("system", 1L + random)
					.build();
			influxDB.write(point);
			Thread.sleep(10);
			System.out.println(Thread.currentThread().getId()+"："+i);
		}
	}
}